package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.ItemCriteria;
import com.leo.ibatis.demo.dao.ItemDao;
import com.leo.ibatis.demo.domain.Item;
import com.leo.ibatis.demo.util.Paging;

public class ItemDaoImpl extends SqlMapClientDaoSupport implements ItemDao {

	public void insert(Item item) throws DataAccessException {
		getSqlMapClientTemplate().insert("Item.insert", item);
	}

	public int update(Item item) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Item.update", item, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(String itemid) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Item.delete", itemid, actualRowsAffected);

		return actualRowsAffected;
	}

	public Item select(String itemid) throws DataAccessException {
		return (Item) getSqlMapClientTemplate().queryForObject("Item.select", itemid);
	}

	@SuppressWarnings("unchecked")
	public List<Item> list(ItemCriteria itemCriteria) throws DataAccessException {
		Assert.notNull(itemCriteria, "itemCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Item.list", itemCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Item> listOnPage(ItemCriteria itemCriteria) throws DataAccessException {
		Assert.notNull(itemCriteria, "itemCriteria must not be null");
		Assert.notNull(itemCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(itemCriteria);
		Paging paging = itemCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Item.list", itemCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(ItemCriteria itemCriteria) throws DataAccessException {
		Assert.notNull(itemCriteria, "itemCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Item.count", itemCriteria)).intValue();
	}

}
